﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;
using HtmlAgilityPack;
using WeiTap.Web;

namespace WeiTap.SearchEngin.Sogou
{
    /// <summary>
    /// 搜狗搜索引擎
    /// </summary>
    public static class SogouClient
    {
        /// <summary>
        /// 搜索公众号的请求地址
        /// </summary>
        public static readonly string SearchWeiChatAccountUrlWithPage = "http://weixin.sogou.com/weixin?type=1&query={0}&page={1}";

        /// <summary>
        /// 图片代理访问
        /// </summary>
        private const string ImageProxyUrl = "http://admin.711688.com.cn/article/ProxyWXImg.ashx?url=";

        /// <summary>
        /// 通过关键字搜索公众号
        /// </summary>
        /// <param name="keyword">关键字</param>
        /// <param name="page">当前页</param>
        /// <param name="recurring">是否翻页</param>
        /// <returns></returns>
        public static async Task<IList<WeiChatAccountModel>> SearchWeiChatAccount(string keyword, int page = 1,bool recurring=true)
        {
            var result = new List<WeiChatAccountModel>();
            try
            {
                var searchUrl = string.Format(SearchWeiChatAccountUrlWithPage, HttpUtility.UrlEncode(keyword), page);
                var www = new HttpFire(searchUrl);
                var helper = new JietuDAL.DateHelp();
                var ds = helper.Select();
                www.Cookies.Add(new Cookie("SNUID", ds.Tables[0].Rows[0][0].ToString(), "/", ".sogou.com"));
                www.Cookies.Add(new Cookie("SUV", ds.Tables[0].Rows[0][1].ToString(), "/", ".sogou.com"));
                
                www.Method = HttpRequestMethod.Get;
                var htmlResult = await www.GetStringAsync();
                var doc = new HtmlDocument();
                doc.LoadHtml(htmlResult);
                var nodes = doc.QuerySelectorAll("div .news-box>ul li");
                var m = doc.QuerySelector("div .mun")?.InnerText.Remove(0,3);
                m = m?.Substring(0, m.IndexOf("条",StringComparison.OrdinalIgnoreCase));
                var maxRecord = 1;
                var maxPage = 1;
                if (int.TryParse(m, out maxRecord))
                {
                    if (maxRecord > 100) maxPage = 11;
                    else
                        maxPage = maxRecord / 10+1;
                }
                foreach (var node in nodes)
                {
                    var label = node.QuerySelector("p .info label");
                    var title = node.QuerySelector("p .tit a");
                    if(label ==null||title==null)Trace.WriteLine("节点出错");
                    var acc = new WeiChatAccountModel
                    {
                        AccountCode = label.InnerText,
                        Name = title.InnerText,
                        NavicationUrl = HttpUtility.HtmlDecode(title.Attributes["href"].Value)
                    };
                    result.Add(acc);
                    
                }
                if (page < maxPage && recurring)
                    result.AddRange(await SearchWeiChatAccount(keyword, page + 1));

            }
            catch (Exception e)
            {
                Trace.WriteLine(e.Message);
            }
            return result;
        }
        /// <summary>
        /// 通过公众号的链接，请求解析文章列表
        /// </summary>
        /// <param name="navigationUrl"></param>
        /// <returns></returns>
        public static IList<WeiChatArticleModel> SearchWeiChatArticles(string navigationUrl)
        {
            throw new NotImplementedException();
        }
        /// <summary>
        /// 通过文章的链接，解析文章的内容
        /// </summary>
        /// <param name="url">文章的链接地址</param>
        /// <returns></returns>
        public static string SearchArticleContent(string url)
        {
            var www = new HttpFire(url) { Method = HttpRequestMethod.Get };
            var htmlResult = www.GetString();
            var reg = new Regex("js_content([\\s\\S]+?)</div>");
            var match = reg.Match(htmlResult);
            if (!match.Success) return string.Empty;
            var result = match.Value.Substring(13);
            result = result.Substring(0, result.Length - 6);
            result = result.Replace("data-src", "src");
            var eva = new MatchEvaluator(WordScrambler);
            result = Regex.Replace(result, "<img[^<>]*?\\ssrc=['\"]?(.*?)['\"].*?>", eva);
            return result;
        }
        /// <summary>
        /// 给原来的图片链接加上代理路径
        /// </summary>
        /// <param name="match"></param>
        /// <returns></returns>
        private static string WordScrambler(Match match)
        {
            var url = match.Groups[1].Value;
            var img = match.Value;
            var realUrl = ImageProxyUrl + url;
            return img.Replace(url, realUrl);
        }
        


    }
}
